<template>
  <div class="app-container">
    <el-form class="multiple-from" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item prop="plotId" label="小区名称：">
        <el-select v-model="queryParams.plotId" placeholder="请选择小区名称" clearable style="width: 170px"
          @change="xiaoquChange">
          <el-option v-for="dict in xiaoquData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="buildId" label="所属楼栋：">
        <el-select v-model="queryParams.buildId" placeholder="请选择楼栋" clearable style="width: 170px"
          @change="loudonChange">
          <el-option v-for="dict in loudongData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择单元：" prop="unit">
        <el-select v-model="queryParams.unit" placeholder="请选择单元">
          <el-option v-for="(item, index) in danyuanData" :key="index" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户分类：" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择用户分类" clearable>
          <el-option v-for="(item, index) in userType" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['house:household:add']">添加住户</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="pilinagHandleCilcik"
          v-hasPermi="['house:household:remove']">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="piliangFengLei"
          v-hasPermi="['house:household:edit']">批量分类</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="piliangBangDing"
          v-hasPermi="['house:household:edit']">批量绑定模型</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['house:household:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['house:household:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="householdList" @selection-change="handleSelectionChange">
      <el-table-column v-if="selectFlag" show-overflow-tooltip type="selection" width="55" align="center" />
      <el-table-column  label="序号" align="center" type="index"></el-table-column>
      <!-- <el-table-column show-overflow-tooltip label="住户id" align="center" prop="id" /> -->
      <el-table-column show-overflow-tooltip label="小区" align="center" prop="plotName">
      </el-table-column>
      <el-table-column show-overflow-tooltip label="楼栋" align="center" prop="buildName" />
      <el-table-column show-overflow-tooltip label="单元号" align="center" prop="unitName" />
      <el-table-column show-overflow-tooltip label="楼层号" align="center" prop="floor" />
      <el-table-column show-overflow-tooltip label="门牌号" align="center" prop="houseNumber">
        <template slot-scope="scope">
          <div @click="goBalancedView(scope.row)" style="color: rgb(64, 158, 255);cursor: pointer;">
            {{ scope.row.houseNumber }}
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="方位" align="center" prop="orientation" />
      <el-table-column show-overflow-tooltip label="管道位置" align="center" prop="pipePosition" />
      <el-table-column show-overflow-tooltip label="采暖面积" align="center" prop="heatArea" />
      <el-table-column show-overflow-tooltip width="100" label="房间热卡号" align="center" prop="hotCardNumber" />
      <el-table-column show-overflow-tooltip label="住户姓名" align="center" prop="userName" />
      <el-table-column show-overflow-tooltip label="固定电话" align="center" prop="landPhone" />
      <el-table-column show-overflow-tooltip label="移动电话" align="center" prop="mobilePhone" />
      <el-table-column show-overflow-tooltip label="供热类型" align="center" prop="heatingType" />
      <el-table-column show-overflow-tooltip label="创建人" align="center" prop="createName" />
      <el-table-column show-overflow-tooltip label="创建时间" align="center" prop="createTime" />
      <el-table-column width="120px" label="当前模型" align="center" prop="customModels">
        <!-- <template slot-scope="scope">
          <div v-for="item, index in scope.row.customModels" :key="index">
            {{ item.modelName }}
          </div>
        </template> -->
        <template slot-scope="scope">
          <el-tooltip placement="top">
            <div slot="content">
              <div style="text-align: center;margin-bottom: 5px;" :key="index"
                v-for="(item, index) in scope.row.customModels ? scope.row.customModels : []">{{ item.modelName }}</div>
            </div>
            <div style="cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              {{ scope.row.customModels && scope.row.customModels.length > 0 ? scope.row.customModels[0].modelName : '' }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="用户分类" align="center" prop="typeName" />
      <el-table-column show-overflow-tooltip label="邮箱" align="center" prop="email" />
      <el-table-column width="150" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="equipmentInfo(scope.row)"
            v-hasPermi="['house:household:edit']">设备详情</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['house:household:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['house:household:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改住户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" class="addOpen" :model="form" :rules="rules" label-position="left" label-width="80px"
        style="display: flex;flex-wrap: wrap;justify-content: space-around;">
        <el-form-item prop="plotId" label="所属小区：">
          <el-select v-model="form.plotId" placeholder="请选择所属小区" clearable style="width: 170px" @change="xiaoquChangeAdd">
            <el-option v-for="dict in xiaoquDataAdd" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="buildId" label="所属楼栋：">
          <el-select v-model="form.buildId" placeholder="请选择楼栋" clearable style="width: 170px" @change="loudonChangeAdd">
            <el-option v-for="dict in loudongDataAdd" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="buildId" label="单元号：">
          <el-select v-model="form.unit" placeholder="请选择单元号" clearable style="width: 170px">
            <el-option v-for="dict in danyuanDataAdd" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="一级模型" prop="modelIds1">
          <el-select v-model="form.modelIds1" placeholder="请选择" @change="$forceUpdate()">
            <el-option
              v-for="(item, index) in CustomModelSelect1"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级模型">
          <el-select v-model="form.modelIds2" placeholder="请选择" multiple @change="$forceUpdate()">
            <el-option
              v-for="(item, index) in CustomModelSelect2"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层号" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层号" />
        </el-form-item>
        <el-form-item label="门牌号" prop="houseNumber">
          <el-input v-model="form.houseNumber" placeholder="请输入门牌号" />
        </el-form-item>
        <el-form-item label="方位" prop="orientation">
          <el-input v-model="form.orientation" placeholder="请输入方位" />
        </el-form-item>
        <el-form-item label="管道位置" prop="pipePosition">
          <el-input v-model="form.pipePosition" placeholder="请输入管道位置" />
        </el-form-item>
        <el-form-item label="采暖面积" prop="heatArea">
          <el-input v-model="form.heatArea" placeholder="请输入采暖面积" />
        </el-form-item>
        <el-form-item label="房间热卡号" prop="hotCardNumber">
          <el-input v-model="form.hotCardNumber" placeholder="请输入房间热卡号" />
        </el-form-item>
        <el-form-item label="供热类型" prop="heatingType">
          <el-input v-model="form.heatingType" placeholder="请输入供热类型" />
        </el-form-item>
        <el-form-item label="住户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入住户姓名" />
        </el-form-item>
        <el-form-item label="固定电话" prop="landPhone">
          <el-input v-model="form.landPhone" placeholder="请输入固定电话" />
        </el-form-item>
        <el-form-item label="移动电话" prop="mobilePhone">
          <el-input v-model="form.mobilePhone" placeholder="请输入移动电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="用户分类" prop="type" style="margin-right: auto;margin-left: 4.5%;">
          <el-select v-model="form.type" placeholder="请选择用户分类" clearable style="width: 170px">
            <el-option v-for="dict in listHouseholdClassify" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="绑定模型" :visible.sync="dialogMx" width="500px" class="bindModel">
      <el-form ref="mxForm" :rules="moxRules" :model="moxForm" style="background: unset">
        <el-form-item label="一级模型:" prop="formModelSelect1">
          <el-select v-model="moxForm.formModelSelect1" placeholder="请选择">
            <el-option v-for="(item, index) in CustomModelSelect1" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级模型:">
          <el-select v-model="moxForm.formModelSelect2" placeholder="请选择" multiple>
            <el-option v-for="(item, index) in CustomModelSelect2" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMx = false">取 消</el-button>
        <el-button type="primary" @click="selectMoxOk">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="住户分类" :visible.sync="dialogFl" width="400px">
      <el-form ref="flForm" :rules="FlRules" :model="FlForm" style="background: unset;padding: 0;margin: 0;">
        <el-form-item label="选择分类:" prop="value" style="">
          <el-select v-model="FlForm.equipmentGroupId" placeholder="请选择">
            <el-option v-for="(item, index) in listHouseholdClassify" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <div style="margin-left: 20px;">
          <el-button @click="openCreate" type="text">新建</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFl = false">取 消</el-button>
        <el-button type="primary" @click="selectFlOk">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设备列表" :visible.sync="dialogSheBei">
      <div><el-button type="primary" @click="addEqu">添加设备</el-button></div>
      <el-table class="scroll_box" :data="shebeiList" style="height: 300px;overflow-y: scroll;">
        <el-table-column show-overflow-tooltip align="center" type="index" label="序号"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="设备种类" prop="equipmentTypeName"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="设备名称" prop="equipmentName"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="设备编号" prop="equipmentCode"></el-table-column>
        <!--<el-table-column show-overflow-tooltip align="center" label="所属楼栋" prop="buildName"></el-table-column>-->
        <!--<el-table-column show-overflow-tooltip align="center" label="所属单元" prop="unitName"></el-table-column>-->
        <!--<el-table-column show-overflow-tooltip align="center" label="房号" prop="householdName"></el-table-column>-->
        <el-table-column show-overflow-tooltip align="center" label="房号">{{ addSheBeiForm.householdName
        }}</el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="详细位置" prop="address"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="所属设备分组" prop="equipmentGroupName"></el-table-column>
        <el-table-column show-overflow-tooltip label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="shebeiEdit(scope.row)"
              v-hasPermi="['build:build:remove']">编辑</el-button>
            <el-button size="mini" type="text" @click="shebeiDel(scope.row)"
              v-hasPermi="['build:build:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="shebeitotal > 0" :total="shebeitotal" :page.sync="shebeiqueryParams.pageNum"
        :limit.sync="shebeiqueryParams.pageSize" @pagination="sheibei" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSheBei = false">取 消</el-button>
        <el-button type="primary" @click="dialogSheBei = false">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改或新增设备 -->
    <el-dialog :title="equTitle" :visible.sync="addShebeiDiaLOG" width="700px">
      <el-form :model="addSheBeiForm" ref="addSheBei" :rules="addSheBeiFormRule"
        style="height:unset;background: unset;margin: 0;padding: 0;display: flex;justify-content: space-between;flex-wrap: wrap;">
        <el-form-item label="房号" prop="householdName" style="margin-bottom:30px;">
          <el-input v-model="addSheBeiForm.householdName" disabled="" placeholder=""></el-input>
        </el-form-item>

        <el-form-item label="dtuId" prop="dtuId" style="margin-bottom: 30px;">
          <el-select v-model="addSheBeiForm.dtuId" placeholder="请选择dtuId" clearable>
            <el-option v-for="dict in dtuIdSelectList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="设备种类" prop="equipmentType" style="margin-bottom:30px;">
          <el-select v-model="addSheBeiForm.equipmentType" placeholder="请选择设备种类" clearable>
            <el-option v-for="(item, index) in shebeiDataAdd" :key="index" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="协议类型" prop="protocolType" style="margin-bottom: 30px;">
          <el-select :disabled="!addSheBeiForm.equipmentType" v-model="addSheBeiForm.protocolType" placeholder="请选择协议类型"
            clearable>
            <el-option v-for="dict in conputedAgreementSelectList" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="设备名称" prop="equipmentName" style="margin-bottom:30px;">
          <el-input v-model="addSheBeiForm.equipmentName" placeholder="设备名称"></el-input>

        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentCode" style="margin-bottom:30px;">
          <el-input v-model="addSheBeiForm.equipmentCode" placeholder="设备编号"></el-input>

        </el-form-item>
        <el-form-item label="设备地址" prop="address" style="margin-bottom:30px;">
          <el-input v-model="addSheBeiForm.address" placeholder="设备地址"></el-input>

        </el-form-item>
        <el-form-item label="设备分组" prop="equipmentGroupId" style="margin-bottom:30px;">
          <!--<el-input v-model="addSheBeiForm.equipmentGroupId" placeholder=""></el-input>-->
          <el-select v-model="addSheBeiForm.equipmentGroupId" placeholder="请选择设备分组" clearable>
            <el-option v-for="(item, index) in shbeiFenZuGroups" :key="index" :label="item.groupName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主动抄表" prop="chabiao" style="position: unset;">
          <el-select v-model="addSheBeiForm.autoRead" placeholder="主动抄表">
            <el-option v-for="(item, index) in chaobiaoData" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addShebeiDiaLOG = false">取 消</el-button>
        <el-button type="primary" @click="isOk">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 用户楼栋对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的楼栋数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { householdList, equipmentListInfo } from "@/api/mock"
// import data5 from "@/utils/data5.json";
import { listHousehold, getHousehold, delHousehold, addHousehold, updateHousehold, setGroupByIds } from "@/api/house/household";
import { listCPlotSelect, listBuildSelect, listBuildUnitSelect, listCustomModelSelect, listHouseholdClassifySelect, listEquipmentGroupSelect } from "@/api/system/utils"
import { listEquipment, getEquipment, addEquipment, updateEquipment, delEquipment } from "@/api/equipment/equipment"
import { addHouseholdClassify } from "@/api/householdClassify/householdClassify";
import { getToken } from "@/utils/auth";
import { batchBindModel } from "@/api/customModel/customModel"
import { dtuSelectList } from "@/api/equipmentMessage/equipmentMessage"
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Household",
  data() {
    return {
      //住户一级模型下拉菜单
      CustomModelSelect1: [],
      //住户二级模型下拉菜单
      CustomModelSelect2: [],
      //住户一级模型选择
      formModelSelect1: [],
      //住户二级模型选择
      formModelSelect2: null,
      // 模型
      dialogMx: false,
      moxForm: {
        formModelSelect1: "",
        formModelSelect2: []
      },
      moxRules: {
        formModelSelect1: [
          { required: true, message: "请选择一级模型", trigger: "change" }
        ],
      },
      // 设备
      equTitle: "",
      shbeiFenZuGroups: "",
      dialogSheBei: false,
      buildId: null,
      unitId: null,
      householdId: null,
      householdName: null,
      lotId: null,
      shebeiList: [],
      dtuIdSelectList: [],
      agreementSelectList: [
        {
          dictLabel: '户用阀门协议',
          dictValue: '1',
        },
        {
          dictLabel: '海马龙阀门协议',
          dictValue: '6',
        },
        {
          dictLabel: '户用热量表协议',
          dictValue: '4',
        },
        {
          dictLabel: '室温采集器协议',
          dictValue: '3',
        },
      ],
      shebeiDataAdd: [],
      shebeiqueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      shebeitotal: 0,

      shebeiFenzu: [
        { label: '楼栋设备组', value: 0 },
        { label: '单元设备组', value: 1 },
        { label: '住户设备组', value: 2 },
      ],

      chaobiaoData: [
        { label: '是', value: '0' },
        { label: '否', value: '1' },
      ],
      // 添加设备
      addShebeiDiaLOG: false,
      addSheBeiForm: {
        id: null,
        buildName: '',
        equipmentType: '',
        equipmentName: '',
        equipmentCode: '',
        xiangxiweizhi: '',
        equipmentGroupId: '',
        protocolType: '',
        chabiao: '',
        equipmentLevel: 3,
      },
      addSheBeiFormRule: {
        dtuId: [
          { required: true, message: "dtuId不能为空", trigger: "blur" }
        ],
        protocolType: [
          { required: true, message: "请选择协议类型", trigger: "blur" },
        ],
        householdName: [
          { required: true, message: "请选择所属用户", trigger: "blur" }
        ],
        equipmentType: [
          { required: true, message: "请选择设备种类", trigger: "blur" }
        ],
        equipmentName: [
          { required: true, message: "请输入设备名称", trigger: "blur" }
        ],
        equipmentCode: [
          { required: true, message: "请输入设备编号", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入设备地址", trigger: "blur" },
          { required: true, min: 14, max: 14, message: "设备地址为14位数字", trigger: "blur" },
        ],
        equipmentGroupId: [
          { required: true, message: "请选择设备分组", trigger: "blur" }
        ],
        autoRead: [
          { required: true, message: "请选择设备类型", trigger: "blur" }
        ],
      },
      // 分类
      dialogFl: false,
      FlForm: {
        equipmentGroupId: null,
        value: null,
      },
      FlRules: {
        equipmentGroupId: [
          { required: true, message: "请选择分类", trigger: "blur" }
        ],
      },
      FlData: [

      ],
      xiaoquData: [],
      loudongData: [],
      danyuanData: [],
      xiaoquDataAdd: [],
      loudongDataAdd: [],
      listHouseholdClassify: [],
      danyuanDataAdd: [],
      userType: [],
      selectFlag: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组
      selects: [],
      // 子表选中数据
      checkedCBuild: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 住户表格数据
      householdList: [],
      // 楼栋表格数据
      cBuildList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unit: null,
        floor: null,
        houseNumber: null,
        userName: null,
        mobilePhone: null,
        heatingType: null,
        areaId: null,
        plotId: null,
        buildId: null,
        type: null,
      },
      // 表单参数
      form: {
        modelIds1:"",
        modelIds2:[]
      },
      // 表单校验
      rules: {
        plotId: [
          { required: true, message: "小区id不能为空", trigger: "blur" }
        ],
        buildId: [
          { required: true, message: "楼栋id不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单元号不能为空", trigger: "blur" }
        ],
        floor: [
          { required: true, message: "楼层号不能为空", trigger: "blur" }
        ],
        houseNumber: [
          { required: true, message: "门牌号不能为空", trigger: "blur" }
        ],
        orientation: [
          { required: true, message: "方位不能为空", trigger: "blur" }
        ],
        pipePosition: [
          { required: true, message: "管道位置不能为空", trigger: "blur" }
        ],
        heatArea: [
          { required: true, message: "采暖面积不能为空", trigger: "blur" }
        ],
        hotCardNumber: [
          { required: true, message: "房间热卡号不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "住户姓名不能为空", trigger: "blur" }
        ],
        mobilePhone: [
          { required: true, message: "移动电话不能为空", trigger: "blur" }
        ],
        heatingType: [
          { required: true, message: "供热类型不能为空", trigger: "change" }
        ],
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        modelIds1: [
          { required: true, message: "请选择一级模型", trigger: "blur" },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/household/importData",
        plotName: '',
      }
    };
  },
  computed: {
    conputedAgreementSelectList() {
      if (this.addSheBeiForm.equipmentType) {
        let obj = this.shebeiDataAdd.find(item => item.dictValue == this.addSheBeiForm.equipmentType)
        return this.agreementSelectList.filter(item => {
          return item.dictLabel.search(obj.dictLabel) != -1
        })
      } else {
        return this.agreementSelectList
      }
    }
  },
  created() {
    //住户一级模型下拉菜单
    listCustomModelSelect({
      "modelType": "3",
      "modelLevel": "1"
    }).then(res => {
      // console.log("小区一级模型下拉菜单",res.rows);
      this.CustomModelSelect1 = res.rows
    })
    //住户二级模型下拉菜单
    listCustomModelSelect({
      "modelType": "3",
      "modelLevel": "2"
    }).then(res => {
      this.CustomModelSelect2 = res.rows
    })

    listCPlotSelect({}).then(res => {
      this.xiaoquData = res.rows
      this.xiaoquDataAdd = res.rows
      this.queryParams.plotId = res.rows[0].value

    }).then(res=>{
      listBuildSelect({ plotId:this.queryParams.plotId}).then((res) => {
          this.loudongData = res.rows;
        });
      this.getList();
    })
  },
  methods: {
    //dtuid选择列表
    getdtuSelectList() {
      if (this.dtuIdSelectList.length <= 0) {
        dtuSelectList({ pageSize: 999 }).then(res => {
          res.rows = res.rows.map(item => {
            item.id = item.id + ''
            return item
          })
          this.dtuIdSelectList = res.rows
        })
      }
    },
    getshebeiData() {
      if (this.shebeiDataAdd.length <= 0) {
        getDicts("equipment_type").then(res => {
          this.shebeiDataAdd = res.data
        });
      }
      // if (this.agreementSelectList.length <= 0) {
      //   getDicts("protocol_type").then(res => {
      //     this.agreementSelectList = res.data
      //   });
      // }
    },
    xiaoquChange() {
      listBuildSelect({ plotId: this.queryParams.plotId }).then(res => {
        this.queryParams.buildId = null;
        this.queryParams.unit = null;
        this.loudongData = res.rows
        this.danyuanData = []
      })
      listHouseholdClassifySelect({ plotId: this.queryParams.plotId }).then(res => {
        this.userType = res.rows
      });
    },
    xiaoquChangeAdd(buildIdNull) {
      if (buildIdNull == null) {
        buildIdNull = true
      }
      listBuildSelect({ plotId: this.form.plotId }).then(res => {
        if (buildIdNull) {
          this.form.buildId = null;
        }
        this.loudongDataAdd = res.rows
      });
      listHouseholdClassifySelect({ plotId: this.form.plotId }).then(res => {
        if (buildIdNull) {
          this.form.type = null;
        }
        this.listHouseholdClassify = res.rows
      });
    },
    loudonChange() {
      listBuildUnitSelect({ buildId: this.queryParams.buildId }).then(res => {
        this.queryParams.unit = null;
        this.danyuanData = res.rows
      });
    },
    loudonChangeAdd(unitIdNull) {
      if (unitIdNull == null) {
        unitIdNull = true
      }
      listBuildUnitSelect({ buildId: this.form.buildId }).then(res => {
        if (unitIdNull) {
          this.queryParams.unit = null;
        }
        this.danyuanDataAdd = res.rows
      });
    },

    /** 设备详情操作 */
    equipmentInfo(row) {
      var id = null;
      if (row != null) {
        id = row.id
        this.buildId = row.buildId;
        this.unitId = row.unit;
        this.householdId = row.id;
        this.householdName = row.houseNumber;
        this.lotId = row.plotId;
        this.setaddSheBeiForm();
      } else {
        id = this.addSheBeiForm.householdId
      }
      this.dialogSheBei = true
      this.loading = true
      listEquipment({ householdId: id }).then(response => {
        this.shebeiList = response.rows;
        this.shebeitotal = response.total
        this.loading = false
      });
      listEquipmentGroupSelect({ plotId: this.addSheBeiForm.lotId }).then(res => {
        this.shbeiFenZuGroups = res.rows
      });
    },
    setaddSheBeiForm() {
      this.addSheBeiForm.buildId = this.buildId;
      this.addSheBeiForm.unitId = this.unitId;
      this.addSheBeiForm.householdId = this.householdId;
      this.addSheBeiForm.householdName = this.householdName;
      this.addSheBeiForm.lotId = this.lotId;
    },
    // 设备修改
    shebeiEdit(row) {
      this.loading = true
      this.getdtuSelectList()
      this.getshebeiData()
      getEquipment(row.id).then(response => {
        this.addSheBeiForm = response.data;
        console.log(this.addSheBeiForm)
        this.setaddSheBeiForm();
        this.addShebeiDiaLOG = true;
        this.equTitle = "修改设备";
        this.loading = false
      });
    },
    // 设备新增
    addEqu() {
      this.resetForm("addSheBei");
      this.equTitle = "新增设备";
      this.getdtuSelectList()
      this.getshebeiData()
      this.addShebeiDiaLOG = true
      this.addSheBeiForm.equipmentLevel = 3
      this.addSheBeiForm.id = null

    },
    // 设备删除
    shebeiDel(row) {
      this.$modal.confirm('是否确认删除设备？').then(function () {
        delEquipment(row.id)
      }).then(() => {
        this.equipmentInfo();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 设备列表
    async sheibei() {
      const res = await equipmentListInfo(this.shebeiqueryParams)
      this.shebeiList = res.rows
      this.shebeitotal = res.total
      console.log(res);
    },
    isOk() {
      this.$refs['addSheBei'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.addSheBeiForm.id != null) {
            this.addSheBeiForm.equipmentLevel =3
            updateEquipment(this.addSheBeiForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.addShebeiDiaLOG = false
              this.equipmentInfo();
              this.loading = false
            });
          } else {
            this.addSheBeiForm.equipmentLevel =3
            addEquipment(this.addSheBeiForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.addShebeiDiaLOG = false
              this.equipmentInfo();
              this.loading = false
            });
          }

        }
      })
    },

    // 选择分类
    selectFlOk() {
      this.$refs['flForm'].validate((valid) => {
        if (valid) {
          this.dialogFl = false
        }
      })
      this.$refs["flForm"].validate(valid => {
        if (valid) {
          const ids = this.ids;
          this.FlForm.ids = ids;
          this.FlForm.lotId = this.selects[0].plotId;
          setGroupByIds(this.FlForm).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.dialogFl = false;
            this.getList();
          });
        }
      });
    },
    /** 查询住户列表 */
    getList() {
      this.loading = true;
      listHousehold(this.queryParams).then(response => {
        this.householdList = response.rows;
        this.total = response.total;
        this.loading = false;
      }, err => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        plotId: null,
        buildId: null,
        unit: null,
        floor: null,
        houseNumber: null,
        orientation: null,
        pipePosition: null,
        heatArea: null,
        hotCardNumber: null,
        userName: null,
        landPhone: null,
        mobilePhone: null,
        heatingType: null,
        email: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        modelIds: null
      };
      this.formModelSelect1 = []
      this.formModelSelect2 = []
      this.cBuildList = [];
      this.resetForm("form");
      this.resetForm("mxForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.loudongData = []
      this.danyuanData = []
      this.userType = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selects = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加住户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHousehold(id).then(response => {
        this.form = response.data;
        if (response.data.modelIds) {
          this.temp(response.data.modelIds, this.CustomModelSelect1)
        }
        
        this.form.buildId == null ? "" : this.form.buildId = this.form.buildId.toString()
        this.form.plotId == null ? "" : this.form.plotId = this.form.plotId.toString()
        this.form.unit == null ? "" : this.form.unit = this.form.unit.toString()
        this.cBuildList = response.data.cBuildList;
        this.xiaoquChangeAdd(false);
        this.loudonChangeAdd(false);
        this.open = true;
        this.title = "修改住户";
        console.log(this.form)
      });
    },
   //一级二级模型回显匹配函数
   temp(modelIds, CustomModelSelect1) {
      let modelIdsList = modelIds.split(",").filter((item) => item !== "");
      console.log("模型数组", modelIdsList);
      console.log("下拉一级模型", CustomModelSelect1);
      if (modelIdsList.length === 1) {
        this.form.modelIds1 = modelIdsList[0];
        return;
      }
      let modelSelect1 = modelIdsList.filter((item) => {
        return CustomModelSelect1.some((item1) => {
          console.log("item1", item1);
          return item1.value == item;
        });
      });
      console.log("一级模型", modelSelect1);
      let modelSelect2 = modelIdsList.filter(
        (item) => item != modelSelect1.toString()
      );
      console.log("二级模型", modelSelect2);
      this.form.modelIds1 = modelSelect1[0];
      this.form.modelIds2 = modelSelect2;
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form.modelIds1, this.form.modelIds2);
      //一级模型和二级模型拼接
      let formModelSelect1 = "," + this.form.modelIds1 + ","
      let formModel = formModelSelect1
      if (this.form.modelIds2 && this.form.modelIds2.length) {
        let formModelSelect2 = this.form.modelIds2.toString() + ","
        formModel = formModelSelect1 + formModelSelect2
      }
      this.form.modelIds = formModel
      console.log(formModel);
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cBuildList = this.cBuildList;
          if (this.form.id != null) {
            updateHousehold(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHousehold(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 批量分类
    piliangFengLei() {
      const ids = this.ids;
      if (this.ids.length === 0) {
        this.selectFlag = !this.selectFlag
      } else {
        const select = this.selects[0];
        var ret = false;
        this.selects.map(item => {
          if (item.plotId != select.plotId) {
            this.$message.error(`只能选一个小区的数据!`);
            ret = true;
          }
        })
        if (ret) {
          return;
        }
        this.FlForm.plotId = select.plotId;
        this.plotName = select.plotName
        this.dialogFl = true;
        this.FlForm.equipmentGroupId = null;
        listHouseholdClassifySelect({ plotId: this.FlForm.plotId }).then(res => {
          this.listHouseholdClassify = res.rows
        });
      }
    },
    // 批量绑定
    piliangBangDing() {
      if (this.ids.length === 0) {
        this.selectFlag = !this.selectFlag
      } else {
        this.dialogMx = true
      }
    },
    // 批量删除
    pilinagHandleCilcik() {
      const ids = this.ids;
      if (this.ids.length === 0) {
        this.selectFlag = !this.selectFlag
      } else {
        this.$modal.confirm('是否删除所选数据？').then(function () {
          return delHousehold(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除住户？').then(function () {
        return delHousehold(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    //批量绑定模型
    pilinagBindModel() {
      // this.reset()
      if (this.ids.length === 0) {
        this.selectFlag = !this.selectFlag
      } else {
        const ids = this.ids;
        console.log(ids);
        this.reset()
        this.dialogMx = true
      }
    },
    // 提交绑定模型
    selectMoxOk() {
      console.log(this.moxForm.formModelSelect1, this.moxForm.formModelSelect2);
      //一级模型和二级模型拼接
      let formModelSelect1 = "," + this.moxForm.formModelSelect1 + ","
      let formModel = formModelSelect1
      if (this.moxForm.formModelSelect2.length) {
        let formModelSelect2 = this.moxForm.formModelSelect2.toString() + ","
        formModel = formModelSelect1 + formModelSelect2
      }
      console.log("模型字符串", formModel);
      console.log("选择的ids", this.ids);
      this.$refs['mxForm'].validate((valid) => {
        if (valid) {
          batchBindModel({
            "type": "3",
            "ids": this.ids,
            "modelIds": formModel,
          }).then(res => {
            this.$modal.msgSuccess("绑定成功");
            this.dialogMx = false
            this.getList();
          })
        }
      })
    },
    /** 楼栋序号 */
    rowCBuildIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 楼栋添加按钮操作 */
    handleAddCBuild() {
      let obj = {};
      obj.buildName = "";
      obj.unitNumber = "";
      obj.floorNumber = "";
      obj.heatingHouseNumber = "";
      obj.totalHouseNumber = "";
      obj.heatArea = "";
      obj.heatMeter = "";
      this.cBuildList.push(obj);
    },
    /** 楼栋删除按钮操作 */
    handleDeleteCBuild() {
      if (this.checkedCBuild.length == 0) {
        this.$modal.msgError("请先选择要删除的楼栋数据");
      } else {
        const cBuildList = this.cBuildList;
        const checkedCBuild = this.checkedCBuild;
        this.cBuildList = cBuildList.filter(function (item) {
          return checkedCBuild.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleCBuildSelectionChange(selection) {
      this.checkedCBuild = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('household/exportHousehold', {
        ...this.queryParams
      }, `住户_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "住户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "household/importTemplate",
        {},
        `住户_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    openCreate() {
      this.$prompt('请输入分类名称', '新建分类', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '分类名称不能为空'
      }).then(({ value }) => {
        this.addHouseholdClass(value)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    //新增住户分类
    addHouseholdClass(classifyName) {
      let plotId = this.FlForm.plotId
      addHouseholdClassify({ plotId, classifyName, plotName: this.plotName }).then(res => {
        this.$message({ type: 'success', message: '新建分类成功' })
        listHouseholdClassifySelect({ plotId }).then(res => {
          this.listHouseholdClassify = res.rows
        });
      })
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    goBalancedView(row) {
      let { plotId, buildId, id } = row
      this.$router.push({
        path: '/balancedView/resident',
        query: {
          plotId: plotId,
          buildId: buildId,
          householdId: id,
        }
      })
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.scroll_box::-webkit-scrollbar {
  width: 0px;
}

.addOpen {
  ::v-deep .el-form-item {
    width: 280px;
  }
}

.bindModel {
  ::v-deep .el-form {
    height: 100% !important;
    background: unset;
    display: block !important;

    .el-form-item {
      margin-left: 40px;
      margin-bottom: 30px !important;
      position: static !important;
    }
  }
}
</style>
